import gobject
import time
import random
import os

from fvutil.managers import objectmanager
from fvutil import fvcon
from util import config

from presence import ps

class ShoppingPresence(ps.ObjectPresence):
    
    def __init__(self, oid, name):
        ps.ObjectPresence.__init__(self, oid, name)
    
class ShoppingManager(objectmanager.ObjectManager):
    
    __gsignals__ = {
            'created_list' : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE,
                    (gobject.TYPE_INT, gobject.TYPE_INT,)),
            'received_list' : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE,
                    (gobject.TYPE_PYOBJECT,)),
    }
    
    # Custom meta keys
    STORE = 13001
    DURATION = 13002 
    ITEMS = 13003
    
    def __init__(self, async, my_id):
        objectmanager.ObjectManager.__init__(self, fvcon.SHOPPING, my_id)
        self.__async = async
        self.__path = config.get('async.folders', str(fvcon.SHOPPING))
        
    def send(self, shopping_list):
        tags = shopping_list['tags']
        items = shopping_list['items']
        dests = shopping_list['recipients']
        expires = time.time() + shopping_list['duration']
        
        meta = {
                fvcon.TAGS: tags,
                ShoppingManager.STORE: shopping_list['store'],
                ShoppingManager.DURATION: shopping_list['duration'],
                ShoppingManager.ITEMS: shopping_list['items']
                }
        
        id = random.randint(1,100000)
        path = os.path.join(self.__path,  str(id) + '.shop')
        f = open(path, mode='wa')
        f.write(str(items))
        f.close()
        assert os.path.exists(path)
        header = self.__async.send_message(path, fvcon.SHOPPING, dests, meta)
        self.add(header)
    
    def receive(self, header):
        self.add(header)
        flash = self.to_flash(header)
        self.emit('received_list', flash )
        
    def to_flash(self, header):
        return {'type':fvcon.SHOPPING,
                'subcommand':fvcon.ADD,
                'id':header.mid,
                'label':header.meta[fvcon.TAGS],
                'time':header.created,
                'authorID':header.src,
                'tags':header.meta[fvcon.TAGS],
                'src':header.src,
                'items':header.meta[ShoppingManager.ITEMS],
                'store':header.meta[ShoppingManager.STORE],
                'duration':header.meta[ShoppingManager.DURATION] }